<template>
  <div class="app-container">
    <el-form
      v-if="false"
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="128px"
    >
      <el-form-item label="轮班编号" prop="classesCode">
        <el-input
          v-model="queryParams.classesCode"
          placeholder="请输入轮班编号"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['planning:planClasses:add']"
        >
          新增
        </el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['planning:planClasses:edit']"
          >编辑</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['planning:planClasses:remove']"
          >删除</el-button
        >
      </el-col> -->
      <!-- <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar> -->
    </el-row>

    <el-table
      v-loading="loading"
      :data="typeList"
      border
      :span-method="objectSpanMethod"
      @selection-change="handleSelectionChange"
    >
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="轮班编号" align="center" prop="classesCode">
        <template #default="scope">
          <el-link type="primary" @click="handleDetail(scope.row)">
            {{ scope.row.classesCode }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column
        label="轮班名称"
        align="center"
        prop="classesName"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="轮班方式"
        align="center"
        prop="classesMode"
        :show-overflow-tooltip="true"
      >
        <template #default="scope">
          <dict-tag :options="shift_mode" :value="scope.row.classesMode" />
        </template>
      </el-table-column>
      <el-table-column
        label="班次名称"
        align="center"
        prop="scheduleName"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="开始时间" align="center" prop="startTime">
        <template #default="scope">
          <span>{{ scope.row.startTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime">
        <template #default="scope">
          <span>{{ scope.row.endTime }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        width="160"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            v-hasPermi="['planning:planClasses:edit']"
            @click="handleUpdate(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            link
            type="primary"
            icon="Delete"
            v-hasPermi="['planning:planClasses:remove']"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog
      :title="title"
      :close-on-click-modal="false"
      v-model="open"
      width="700px"
      append-to-body
    >
      <el-form
        ref="formRef"
        :disabled="disabledForm"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="轮班编号" prop="classesCode">
          <code-input
            v-model="form.classesCode"
            code="SHIFT_CODE"
            :disabled="!!form.id"
            placeholder="请输入轮班编号"
          />
        </el-form-item>
        <el-form-item label="轮班名称" prop="classesName">
          <el-input v-model="form.classesName" placeholder="请输入轮班名称" />
        </el-form-item>
        <el-form-item label="轮班方式" prop="classesMode">
          <el-radio-group v-model="form.classesMode" @change="modeChange">
            <el-radio
              v-for="dict in shift_mode"
              :key="dict.value"
              :value="dict.value"
              :disabled="!!form.id"
            >
              {{ dict.label == "白班" ? "一班" : dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-for="(el, index) in form.planClassesScheduleList"
          :key="index"
          :label="el.scheduleName"
          prop="planClassesScheduleList"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="开始时间" prop="startTime">
                <el-time-picker
                  v-model="el.startTime"
                  :clearable="false"
                  value-format="HH:mm:ss"
                  placeholder="请选择开始时间"
                ></el-time-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="结束时间" prop="endTime">
                <el-time-picker
                  v-model="el.endTime"
                  :clearable="false"
                  value-format="HH:mm:ss"
                  placeholder="结束时间"
                ></el-time-picker>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :maxlength="200"
            show-word-limit
            placeholder="请输入内容"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button v-if="!disabledForm" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ShiftMaintenance">
import {
  listShift,
  getShift,
  delShift,
  addShift,
  updateShift,
} from "@/api/base/plan/shiftMgt/shiftMaintenance";
import { SHIFT_MODE } from "../config";
import { ref, toRefs, reactive, getCurrentInstance } from "vue";

const { proxy } = getCurrentInstance();
const { shift_mode } = proxy.useDict("shift_mode");

const typeList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const disabledForm = ref(false);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
  },
  rules: {
    classesCode: [{ required: true, message: "轮班编号不能为空", trigger: "change" }],
    classesName: [{ required: true, message: "轮班名称不能为空", trigger: "change" }],
    classesMode: [{ required: true, message: "请选择轮班方式", trigger: "change" }],
  },
});

const { queryParams, form, rules } = toRefs(data);
const shiftMode = SHIFT_MODE;
/** 查询设备类型列表 */
function getList() {
  loading.value = true;
  listShift(proxy.addDateRange(queryParams.value, dateRange.value)).then((response) => {
    const list = [];
    response.rows.forEach((el) => {
      if (el?.planClassesScheduleList?.length) {
        el.planClassesScheduleList.forEach((item, index) => {
          list.push({
            ...item,
            ...el,
            row: index == 0 ? el?.planClassesScheduleList?.length : 0,
          });
        });
      } else {
        list.push({
          ...el,
          row: 1,
        });
      }
    });
    typeList.value = list;
    console.log(list);

    total.value = response.total;
    loading.value = false;
  });
}

const objectSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  console.log(row, column, rowIndex, columnIndex, "===sobjectSpanMethod");
  if (columnIndex !== 4 && columnIndex !== 5) {
    const _col = row.row > 0 ? 1 : 0;
    return {
      rowspan: row.row,
      colspan: _col,
    };
  }
};

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    classesCode: "",
    classesName: "",
    classesMode: "2",
    planClassesScheduleList: [],
    remark: "",
  };
  const current = shiftMode[1].children;
  current.forEach((item) => {
    item.classesCode = form.value.classesCode;
  });

  form.value.planClassesScheduleList = current;
  proxy.resetForm("formRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

function modeChange(value) {
  const current = shiftMode[value - 1].children;
  current.forEach((item) => {
    item.classesCode = form.value.classesCode;
  });

  form.value.planClassesScheduleList = current;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  disabledForm.value = false;
  open.value = true;
  title.value = "新增轮班";
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

function handleDetail(row) {
  reset();
  const typeId = row.id;
  disabledForm.value = true;
  getShift(typeId).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "班次详情";
  });
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const typeId = row.id || ids.value;
  disabledForm.value = false;
  getShift(typeId).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "编辑轮班";
  });
}

/** 提交按钮 */
function submitForm() {
  console.log(form.value);
  proxy.$refs["formRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != undefined) {
        updateShift(form.value).then(() => {
          proxy.$modal.msgSuccess("编辑成功");
          open.value = false;
          getList();
        });
      } else {
        addShift(form.value).then(() => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const ids = row.id;
  let msg = "";
  if (row.classesCode) {
    msg = `是否确认删除轮班编号为"${row.classesCode}"数据项？`;
  } else {
    msg = `是否确认删除所选数据项？`;
  }
  proxy.$modal
    .confirm(msg)
    .then(function () {
      return delShift(ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

getList();
</script>
